package cn.spike.rockcc.utils;

import cn.spike.rockcc.domain.AlipayInfo;
import cn.spike.rockcc.domain.PayFlow;
import cn.spike.rockcc.domain.PayOrder;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;

public class AliPayUtils {


    public static String createAliPay(PayOrder payOrder, AlipayInfo alipayInfo) {
        // 1. 设置参数（全局只需设置一次）
        Factory.setOptions(getOptions(alipayInfo));
        try {
            /*
            String subject, String outTradeNo, String totalAmount, String returnUrl
             */
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(
                    payOrder.getSubject(),
                    payOrder.getOrderNo(),
                    payOrder.getAmount().toString(),
                    alipayInfo.getReturnUrl());
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                return response.getBody();
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }

    public static String drawback(PayFlow payFlow) {
        // 1. 设置参数（全局只需设置一次）
        //Factory.setOptions(getOptions(alipayInfo));
        try {
            /*
            String outTradeNo, String refundAmount
             */
            String totalAmount = payFlow.getTotalAmount().toString();
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(
                    payFlow.getOutTradeNo(),totalAmount
            );
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                return response.getHttpBody();
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return null;
    }


    private static Config getOptions(AlipayInfo alipayInfo) {
        Config config = new Config();
        config.protocol = alipayInfo.getProtocol();
        config.gatewayHost = alipayInfo.getGatewayHost();
        config.signType = "RSA2";
        config.appId = alipayInfo.getAppId();
        config.merchantPrivateKey = alipayInfo.getMerchantPrivateKey();
        config.alipayPublicKey = alipayInfo.getAlipayPublicKey();
        config.notifyUrl = alipayInfo.getNotifyUrl();
        return config;
    }
}
